package com.wrial.face;
/*
 * @Author  Wrial
 * @Date Created in 19:20 2020/8/20
 * @Description  设计4个线程，其中两个线程每次向List集合list中添加一个元素
 *              另外两个线程每次从集合中取出并删除一个元素。
 */

import javax.swing.*;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

public class ThreadTest {

    private static LinkedList<Integer> share = new LinkedList<>();
    private static volatile int state = 0;
    private static Object lock = new Object();

    public static void main(String[] args) {
        Thread thread1 = new Thread(() -> {
            while (state != 0) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            share.add(0);
            System.out.println("put" + 0);
            state = 1;
            lock.notifyAll();
        });
        Thread thread2 = new Thread(() -> {
            while (state != 1) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            share.add(1);
            System.out.println("put" + 1);
            state = 2;
            lock.notifyAll();
        });
        Thread thread3 = new Thread(() -> {
            while (state != 2) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("remove" + share.remove(0));
            state = 3;
            lock.notifyAll();
        });
        Thread thread4 = new Thread(() -> {
            while (state != 3) {
                try {
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("remove" + share.remove());
            state = 0;
            lock.notifyAll();
        });
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }


}
